// tools/scripts/smart-dev.js

import { execSync, spawn } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, resolve } from 'path';
import readline from 'readline';

const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = resolve(__dirname, '../..');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// 检测当前操作系统
const isWindows = process.platform === 'win32';

// 构造适合当前系统的命令
function getCommand(pkgPath, script) {
  if (isWindows) {
    // Windows环境下使用绝对路径和powershell
    const fullPath = resolve(rootDir, pkgPath);
    return `cd "${fullPath}" && pnpm run ${script}`;
  } else {
    // Unix-like环境下的命令
    return `cd ${pkgPath} && pnpm run ${script}`;
  }
}

const scenarios = {
  full: {
    name: '完整环境',
    commands: [
      { name: '主应用', cmd: getCommand('apps/microfrontend-host', 'dev') },
      { name: '认证微应用', cmd: getCommand('packages/micro-auth', 'dev') },
      { name: '仪表板微应用', cmd: getCommand('packages/micro-dashboard', 'dev') },
      { name: '用户微应用', cmd: getCommand('packages/micro-user', 'dev') },
    ]
  },
  minimal: {
    name: '最小化环境',
    commands: [
      { name: '主应用', cmd: getCommand('apps/microfrontend-host', 'dev') },
      { name: '仪表板微应用', cmd: getCommand('packages/micro-dashboard', 'dev') },
    ]
  },
  legacy: {
    name: '仅老应用',
    commands: [
      { name: '老应用', cmd: getCommand('apps/legacy-vue2-app', 'serve') },
    ]
  },
  hostOnly: {
    name: '仅主应用',
    commands: [
      { name: '主应用', cmd: getCommand('apps/microfrontend-host', 'dev') }
    ]
  }
};

function runCommand(command, name) {
  console.log(`🚀 启动 ${name}...`);
  
  const child = spawn(command, {
    shell: true,
    stdio: 'pipe'
  });

  child.stdout.on('data', (data) => {
    console.log(`[${name}] ${data.toString().trim()}`);
  });

  child.stderr.on('data', (data) => {
    console.error(`[${name}-ERROR] ${data.toString().trim()}`);
  });

  return child;
}

async function startDevelopment() {
  console.log('🎯 选择启动模式:');
  console.log('1. 完整环境 (所有应用)');
  console.log('2. 最小化环境 (主应用 + 仪表板)');
  console.log('3. 仅主应用');
  console.log('4. 自定义选择');

  rl.question('请选择 (1-4): ', async (choice) => {
    let selectedScenario;
    
    switch (choice) {
      case '1':
        selectedScenario = scenarios.full;
        break;
      case '2':
        selectedScenario = scenarios.minimal;
        break;
      case '3':
        selectedScenario = scenarios.hostOnly;
        break;
      case '4':
        // 自定义选择逻辑
        await customSelection();
        return;
      default:
        console.log('使用默认模式: 仅主应用');
        selectedScenario = scenarios.hostOnly;
    }

    console.log(`\n🔄 启动 ${selectedScenario.name}...\n`);
    
    const processes = selectedScenario.commands.map(({ cmd, name }) => 
      runCommand(cmd, name)
    );

    // 优雅关闭
    process.on('SIGINT', () => {
      console.log('\n🛑 正在关闭所有服务...');
      processes.forEach(child => child.kill('SIGINT'));
      process.exit(0);
    });
  });
}

async function customSelection() {
  // 实现自定义选择逻辑
  console.log('自定义选择功能待实现');
  rl.close();
}

// 检查并安装 concurrently
try {
  execSync('npm list concurrently', { stdio: 'ignore' });
} catch {
  console.log('📦 安装 concurrently...');
  execSync('npm install -g concurrently', { stdio: 'inherit' });
}

startDevelopment();